<template>
  <div>
    <el-upload
      ref="uploadImages"
      action="http://localhost:8080"
      list-type="picture-card"
      accept="image/jpeg,image/png"
      :file-list="fileList"
      :before-upload="beforeAvatarUpload"
      >
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{file}">
        <img
          class="avatar"
          :src="file.url" alt=""
        >
        <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          class="el-upload-list__item-delete"
          @click="handleDownload(file)"
        >
          <i class="el-icon-download"></i>
        </span>
        <span
          class="el-upload-list__item-delete"
          @click="handleRemoveImage(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
        <span
          class="el-upload-list__item-rename"
          @click="handleEdit(file)"
        >
          <i class="el-icon-edit"></i>
        </span>
      </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="imageUrl" alt="">
    </el-dialog>
    <el-dialog title="重命名" :visible.sync="editVisible" width="30%" center>
      <el-autocomplete
        class="inline-input" 
        v-model="newName"
        :fetch-suggestions="querySearch"
        placeholder="请输入"
        :trigger-on-focus="false" clearable
      ></el-autocomplete>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRename">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        baseUrl: "http://localhost:8080/",
        dialogVisible: false,
        editVisible: false,
        oldName: "",
        newName: "",
        imageUrl: "",
        downloadUrl: "",
        fileList: []
      };
    },
    mounted() {
      this.initImages();
    },
    methods: {
      initImages() {
        var that = this;
        const xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (this.status == 200) {
            const response = JSON.parse(this.responseText);
            that.fileList = [];
            for (let url of response.files) {
              let arr = url.split("/");
              let name = arr[arr.length - 1];
              that.fileList.push({name, url});
            }
          }
        };
        xhttp.open("GET", this.baseUrl , false);
        xhttp.send();
      },
      beforeAvatarUpload(file) {
        const isAccept= file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isAccept) {
          this.$message.error('上传的图片只能是 JPG或PNG 格式!');
          return false;
        }
        if (!isLt2M) {
          this.$message.error('上传的图片大小不能超过 2MB!');
          return false;
        }
        return isAccept && isLt2M;
      },
      handlePictureCardPreview(file) {
        this.imageUrl = file.url;
        this.dialogVisible = true;
      },
      handleDownload(file){
        const aLink = document.createElement("a");
        aLink.href = this.baseUrl + "files/" + file.name;
        aLink.click();
      },
      handleRemoveImage(file) {
        this.$refs.uploadImages.handleRemove(file);
      },
      handleEdit(file) {
        this.oldName = file.name
        this.editVisible = true;
      },
      querySearch(queryString, cb) {
        var restaurants = [{"value":"张三"}, {"value":"李四"}];
        var results = queryString ? restaurants.filter(
          restaurant => (restaurant.value.indexOf(queryString) === 0)) : restaurants;
        cb(results);
      },
      handleRename() {
        var newName = this.newName + "." + this.oldName.split(".")[1];
        const xhttp = new XMLHttpRequest();
        var that = this;
        xhttp.onreadystatechange = function() {
          if (this.status == 200) {
            that.$message({
              message: '重命名成功',
              center: true,
              type: 'success',
              duration: 1000
            });
          }
        };
        xhttp.open("PUT", `${this.baseUrl}file/rename?oldName=${this.oldName}&newName=${newName}`, false);
        xhttp.send();
        this.editVisible = false;
      },
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .inline-input {
    padding-left: 10%;
  }
</style>